package com.zhanglifan.action;

import com.zhanglifan.domain.Module;
import com.zhanglifan.domain.Role;
import com.zhanglifan.domain.User;
import com.zhanglifan.service.UserService;
import com.zhanglifan.util.SysConstant;
import com.zhanglifan.util.UtilFuns;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import java.util.Set;


public class LoginAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private UserService userService;

	private String username;
	private String password;



	//SSH传统登录方式
	public String login() throws Exception {

	    try{
            if (UtilFuns.isEmpty(username)){
                return "login";
            }

            Subject subject = SecurityUtils.getSubject();

            UsernamePasswordToken upToken = new UsernamePasswordToken(username,password);

            subject.login(upToken);

            User user = (User) subject.getPrincipal();

            System.out.println("*** user.getDept() 的值是: " + user.getDept() + " ***");

            Set<Role> roles = user.getRoles();

            for (Role role:
                    roles) {
                Set<Module> modules = role.getModules();
                for (Module module:
                        modules) {
                    System.out.println("*** module 的值是: " + module.getCpermission() + " ***");
                }
            }

            session.put(SysConstant.CURRENT_USER_INFO,user);

            System.out.println("*** username 的值是: " + username + " ***");
            System.out.println("*** password 的值是: " + password + " ***");

//		if(true){
//			String msg = "aaaaa登录错误，请重新填写用户名密码!";
//			this.addActionError(msg);
//			throw new Exception(msg);
//		}
//            User user =new User(username,password);
//            User login =  userService.findUserByUserName(username);
        }catch (Exception e){
            e.printStackTrace();

            request.put("errorInfo","用户名或密码错误");
            return "login";
        }


//		if (login != null) {
//			ActionContext.getContext().getValueStack().push(user);
//			session.put(SysConstant.CURRENT_USER_INFO, login);	//记录session
//			return SUCCESS;
//		}
//
//		return "login";


		return SUCCESS;
	}
	
	
	//退出
	public String logout(){
		session.remove(SysConstant.CURRENT_USER_INFO);		//删除session
		SecurityUtils.getSubject().logout();
		return "logout";
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}

